package com.linkstec.mot.util;

import java.io.UnsupportedEncodingException;

import com.linkstec.mot.cons.Constants;

/**
 * @author PENGYAO
 * 
 */
public class StringLenUtil {
	public static int getUTF8ByteLength(String str) {
		int result = 0;
		try {
			result = getByteLength("utf-8", str);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * GBK编码下一个汉字占用两个字节。
	 * 
	 * @param str
	 * @return
	 */
	public static int getGbkByteLength(String str) {
		int result = 0;
		try {
			result = getByteLength("gbk", str);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return result;
	}

	private static int getByteLength(String bianma, String str)
			throws UnsupportedEncodingException {
		if (isNullOrEmpty(str)) {
			return 0;
		}
		int res = 0;
		try {
			res = str.getBytes(bianma).length;
		} catch (UnsupportedEncodingException e) {
			throw e;
		}
		return res;
	}

	public static boolean isNullOrEmpty(String str) {
		if (str == null)
			return true;
		if (str.length() == 0)
			return true;
		return str.trim().length() == 0;
	}

	public static String subStringByBytes(String str, int end) {
		// 获取一个汉字占用字节
		int len = getCharByteLen();
		if (str.length() * len < end) {
			return str;
		}
		char[] chArr = str.toCharArray();
		int lenByte = 0;
		for (int i = 0; i < chArr.length; i++) {
			if (chArr[i] > 255) {// char的ascⅡ值大于255表示汉字
				lenByte += len;
			} else {
				++lenByte;
			}
			if (lenByte >= end) {
				if (lenByte == end) {
					return new String(str.substring(0, i + 1));
				}
				return new String(str.substring(0, i));
			}
		}
		return str;
	}

	/**
	 * 10.中文汉字：人
	 * 
	 * 11.字节数：2;编码：GB2312
	 * 
	 * 12.字节数：2;编码：GBK
	 * 
	 * 13.字节数：2;编码：GB18030
	 * 
	 * 14.字节数：1;编码：ISO-8859-1
	 * 
	 * 15.字节数：3;编码：UTF-8
	 * 
	 * 16.字节数：4;编码：UTF-16
	 * 
	 * 17.字节数：2;编码：UTF-16BE
	 * 
	 * 18.字节数：2;编码：UTF-16LE
	 * 
	 * @return
	 */
	private static int getCharByteLen() {
		int len = 2;
		if ("utf-8".equalsIgnoreCase(Constants.DATABASE_ENCODING)) {
			len = 3;
		} else if ("gbk".equalsIgnoreCase(Constants.DATABASE_ENCODING)) {
			len = 2;
		}
		return len;
	}
}
